//
//  WebViewController.m
//  WebView
//
//  Created by 沈煜航 on 2019/2/14.
//  Copyright © 2019 沈煜航. All rights reserved.
//

#import "WebViewController.h"
#import "AppDelegate.h"


@interface WebViewController ()

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _url = @"https://www.baidu.com";   //获取URL
    
    // 初始化webview
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-60)];
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.delegate = self;
    _webView.delegate = self;
    _webView.backgroundColor = [UIColor clearColor];
    [_webView setScalesPageToFit:YES];
    
    // 初始化加载转轮
    activityIndicatorView = [[UIActivityIndicatorView alloc]
                             initWithFrame : CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ;
    [activityIndicatorView setCenter: self.view.center] ;
    // 设置转轮样式
    [activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleGray] ;
    [self.view addSubview:_webView];
    [self.view addSubview : activityIndicatorView] ;
    
    // 判断URL样式，使用不同的加载方式
    if ([_url isKindOfClass:[NSString class]]) {
        [self loadWebPageWithString:_url];
    }else{
        NSURLRequest *request =[NSURLRequest requestWithURL:_url];
        [_webView loadRequest:request];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    AppDelegate *_rootDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [_rootDelegate.draverView hide];
}

- (void)loadWebPageWithString:(NSString*)urlString
{
    self.url = urlString;
    NSURL *url =[NSURL URLWithString:urlString];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
}

#pragma mark - UIWebViewDelegate
/* 返回NO表示不允许加载这个请求 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView{
    //展示风火轮
    [activityIndicatorView startAnimating] ;
}
// 完成加载
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //停止风火轮
    [activityIndicatorView stopAnimating];
}
// 加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [activityIndicatorView stopAnimating];
    if([error code] == NSURLErrorCancelled){
        return;
    }
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint point = scrollView.contentOffset;
    if (point.x > 0 || point.x < 0) {
        //网页滚动时控制水平位置
        scrollView.contentOffset = CGPointMake(0, point.y);
    }
}

@end
